<template>
  <div class="signature-container">
    <div class="canvas-wrapper">
      <canvas
        ref="canvas"
        @mousedown="startDrawing"
        @mousemove="draw"
        @mouseup="endDrawing"
        @mouseleave="endDrawing"
      ></canvas>
    </div>

    <div class="button-group">
      <el-button type="danger" @click="clearCanvas">清空</el-button>
      <el-button type="primary" @click="confirmSignature">确认签名</el-button>
      <el-button type="primary" @click="cancel">取消</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SignaturePad',
  props: {
    width: {
      type: Number,
      default: 630
    },
    height: {
      type: Number,
      default: 310
    }
  },
  data() {
    return {
      isDrawing: false,
      lastX: 0,
      lastY: 0,
      ctx: null,
      ratio: 1
    }
  },
  mounted() {
    this.initCanvas()
  },
  methods: {
    cancel() {
      this.$emit('cancel')
    },
    initCanvas() {
      const canvas = this.$refs.canvas
      this.ratio = window.devicePixelRatio || 1

      // 设置canvas实际大小
      canvas.width = this.width * this.ratio
      canvas.height = this.height * this.ratio

      // 设置canvas显示大小
      canvas.style.width = this.width + 'px'
      canvas.style.height = this.height + 'px'

      this.ctx = canvas.getContext('2d')
      this.ctx.scale(this.ratio, this.ratio)
      this.ctx.lineWidth = 2
      this.ctx.lineCap = 'round'
      this.ctx.strokeStyle = '#000'
    },

    startDrawing(e) {
      this.isDrawing = true
      const rect = this.$refs.canvas.getBoundingClientRect()
      this.lastX = (e.clientX - rect.left) * (this.width / rect.width)
      this.lastY = (e.clientY - rect.top) * (this.height / rect.height)
    },

    draw(e) {
      if (!this.isDrawing) return

      const rect = this.$refs.canvas.getBoundingClientRect()
      const x = (e.clientX - rect.left) * (this.width / rect.width)
      const y = (e.clientY - rect.top) * (this.height / rect.height)

      this.ctx.beginPath()
      this.ctx.moveTo(this.lastX, this.lastY)
      this.ctx.lineTo(x, y)
      this.ctx.stroke()

      this.lastX = x
      this.lastY = y
    },

    endDrawing() {
      this.isDrawing = false
    },

    clearCanvas() {
      this.ctx.clearRect(0, 0, this.width, this.height)
      this.$emit('clear')
    },

    async confirmSignature() {
      try {
        if (this.isCanvasBlank()) {
          this.$modal.msgError("请签名后提交！");
          return false;
        }
        const blob = await this.getSignatureBlob()
        this.$emit('confirm', blob)
      } catch (error) {
        this.$emit('error', error)
      }
    },
    // 添加一个方法来检查Canvas是否被绘制
    isCanvasBlank() {
      const canvas = this.$refs.canvas;
      const ctx = canvas.getContext('2d');
      const pixelData = ctx.getImageData(0, 0, canvas.width, canvas.height).data;

      for (let i = 0; i < pixelData.length; i += 4) {
        // 检查每个像素的透明度
        // 如果任何像素的RGBA值不是完全透明的，则返回false
        if (pixelData[i + 3] !== 0) { // Alpha channel is not 0
          return false;
        }
      }
      return true;
    },
    getSignatureBlob() {
      return new Promise((resolve, reject) => {
        const canvas = this.$refs.canvas

        // 创建临时canvas用于生成图片
        const tempCanvas = document.createElement('canvas')
        const tempCtx = tempCanvas.getContext('2d')

        tempCanvas.width = canvas.width
        tempCanvas.height = canvas.height
        tempCtx.drawImage(canvas, 0, 0)

        tempCanvas.toBlob(blob => {
          if (blob) {
            resolve(blob)
          } else {
            reject(new Error('Canvas转Blob失败'))
          }
        }, 'image/png')
      })
    }
  }
}
</script>

<style scoped>
.signature-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 20px;
}

.canvas-wrapper {
  background: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

canvas {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background: white;
}

.button-group {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
